const {
  createInformation,
  updateInformation,
  removeInformation,
  restoreInformation,
  findInformation,
  findInformationInfo,
  updateInformationRecord
} = require("../service/information.service");

const {
  findIsCollect
} = require("../service/collect.service");
const { sucOperation } = require("../constant/success.type");
const { failOperation } = require("../constant/err.type");

class InformationController {
  async updateInformationRecord(ctx, next) {
    try {
      const {record_info} = await findInformationInfo(ctx.params.id)
      await updateInformationRecord(
          record_info.id, ctx.request.body.type
      );
      ctx.body = {
        ...sucOperation,
      };
    } catch (err) {
      return (ctx.body = {
        ...failOperation,
      });
    }
  }
  async create(ctx, next) {
    try {
      const { createdAt, updatedAt, ...res } = await createInformation(
        ctx.request.body
      );
      ctx.body = {
        ...sucOperation,
        result: res,
      };
    } catch (err) {
      return (ctx.body = {
        ...failOperation,
      });
    }
  }

  async update(ctx) {
    try {
      const res = await updateInformation(ctx.params.id, ctx.request.body);
      console.log(res);
      if (res) {
        ctx.body = {
          ...sucOperation,
          result: res,
        };
      } else {
        return (ctx.body = {
          ...failOperation,
        });
      }
    } catch (err) {
      console.error(err);
    }
  }

  async remove(ctx) {
    const res = await removeInformation(ctx.params.id);

    if (res) {
      ctx.body = {
        ...sucOperation,
      };
    } else {
      return (ctx.body = {
        ...failOperation,
      });
    }
  }

  async restore(ctx) {
    const res = await restoreGoods(ctx.params.id);
    if (res) {
      ctx.body = {
        ...sucOperation,
      };
    } else {
      return (ctx.body = {
        ...failOperation,
      });
    }
  }

  async findAll(ctx) {
    // 1. 解析pageNum和pageSize
    const { pageNum = 1, pageSize = 10, ...params } = ctx.request.body;
    // 2. 调用数据处理的相关方法
    const res = await findInformation({ pageNum, pageSize, ...params });
    // 3. 返回结果
    ctx.body = {
      ...sucOperation,
      result: res,
    };
  }

  async findOne(ctx) {
    const { id } = ctx.params;
    const result = await findInformationInfo(id);
    const {id:user_id} = ctx.state.user
    const isCollect = await findIsCollect({user_id,info_id:id})

    if (result) {
      ctx.body = {
        ...sucOperation,
        result:{
          ...result,
          isCollect
        },
      };
    } else {
      ctx.body = {
        code: 500,
        message: "id有误",
      };
    }
  }
}

module.exports = new InformationController();
